/*
 * XlsApi.cpp
 *
 *  Created on: 2016-10-12
 *      Author: root
 */

#include"PublicXls.h"
#if USE_PUBLIC_XLS
#include <stdarg.h>
PublicXls::PublicXls(){
	m_fp=NULL;
}
PublicXls::~PublicXls(){
	if(m_fp!=NULL){
		Xls_CloseFile();
	}
}
int PublicXls::Xls_CreateFile(const char*FileName){
	 m_fp=fopen(FileName,"wb");
	 if(m_fp==NULL)return -1;
	 fprintf(m_fp,"<?xml version=\"1.0\"?>\r\n");
	 fprintf(m_fp,"<?mso-application progid=\"Excel.Sheet\"?>\r\n");
	 fprintf(m_fp,"<Workbook "
				  "xmlns:x=\"urn:schemas-microsoft-com:office:excel\" "
				  "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" "
				  "xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">\r\n");
	 return 0;
}
int PublicXls::Xls_CreateSheet(const char*SheetName){
	 if(m_fp==NULL)return -1;
    fprintf(m_fp,"<Worksheet ss:Name=\"%s\">\r\n",SheetName);
	 fprintf(m_fp,"<ss:Table>\r\n");
	 return 0;
}
int PublicXls::Xls_CloseSheet(){
	 if(m_fp==NULL)return -1;
    fprintf(m_fp,"</ss:Table>\r\n");
    fprintf(m_fp,"</Worksheet\r\n");
    return 0;
}
int PublicXls::Xls_CloseFile(){
	 if(m_fp==NULL)return -1;
	 fprintf(m_fp,"</Workbook>\r\n");
	 fclose(m_fp);
	 m_fp=NULL;
	 return 0;
}
int PublicXls::Xls_WriteRawData(const char*fmt,...){
	 va_list st;
	 const char*pos=fmt;
	 fprintf(m_fp,"<ss:Row>\r\n");
	 va_start(st,fmt);
	 while(pos[0]!='\0'){
		 char type=pos[0];
		 switch(type){
		 case 's':{
			 const char*str=va_arg(st,const char*);
			 fprintf(m_fp,"<ss:Cell><Data ss:Type=\"String\">%s</Data></ss:Cell>\r\n",str);
		 	 }
			 break;
		 case 'd':{
			 int number=va_arg(st,int);
			 fprintf(m_fp,"<ss:Cell><Data ss:Type=\"String\">%d</Data></ss:Cell>\r\n",number);
		 	 }
			 break;
       case 'f':{
          double number=va_arg(st,double);
          fprintf(m_fp,"<ss:Cell><Data ss:Type=\"String\">%0.2f</Data></ss:Cell>\r\n",number);
             }
          break;
		 default:
			 break;
		 }
		 pos++;
	 }
	 va_end(st);
	 fprintf(m_fp,"</ss:Row>\r\n");
	 return 0;
}
#endif
